﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Mad.Nug.Controls
{
    public class CommandButton : Button
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public CommandButton()
        {
        }

        /// <summary>
        /// Command Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty CommandProperty =
                               DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandButton),
                                                                   new PropertyMetadata((ICommand)null, null));

        /// <summary>
        /// Get the command specified
        /// </summary>
        /// <param name="originalDependencyObject"></param>
        /// <returns></returns>
        public static ICommand GetCommand(DependencyObject originalDependencyObject)
        {
            if (originalDependencyObject != null)
                return (ICommand)originalDependencyObject.GetValue(CommandProperty);

            return null;
        }

        /// <summary>
        /// Set the specified command
        /// </summary>
        /// <param name="originalDependencyObject"></param>
        /// <param name="value"></param>
        public static void SetCommand(DependencyObject originalDependencyObject, ICommand value)
        {
            if (originalDependencyObject != null)
                originalDependencyObject.SetValue(CommandProperty, value);
        }

        /// <summary>
        /// Process button onclick, first let execute the event.
        /// </summary>
        protected override void OnClick()
        {
            base.OnClick();

            ICommand command = (ICommand)this.GetValue(CommandProperty);
            if (command != null)
                command.Execute(null);
        }
    }
}
